<template>
  <view class="resume-page">
    <!-- 顶部标题栏（带返回按钮） -->
    <view class="title-bar">
      <image 
        class="back-icon" 
        src="/static/icons/left.png" 
        mode="widthFix"
        @click="navigateBack"
        alt="返回"
      ></image>
      <text class="title">我的在线简历</text>
    </view>

    <!-- 个人信息区域 -->
    <view class="personal-info">
      <view class="info-left">
        <view class="name-area">
          <text class="name">{{ userInfo.username }}</text>
          <image 
            class="edit-icon" 
            src="/static/icons/edit.png" 
            mode="widthFix"
            @click="navigateToPersonalEdit"
            alt="编辑"
          ></image>
        </view>
        <text class="other-info">{{ userInfo.age }}岁 · {{ degreeMap[userInfo.degree] || '未填写' }}</text>
        <view class="contact-info">
          <image class="contact-icon" src="/static/icons/telephone.png" mode="widthFix" alt="电话"></image>
          <text>{{ userInfo.telephone }}</text>
        </view>
      </view>
      <image 
        class="avatar" 
        :src="userInfo.headIcon" 
        mode="aspectFill"
        alt="用户头像"
        @error="handleAvatarError"
      ></image>
    </view>

    <view class="section">
      <text class="section-title">求职状态</text>
      <picker mode="selector" :range="jobSearchStatusText" :value="jobStatusIndex" @change="onJobStatusChange">
        <view class="job-status">
          <text>{{ jobSearchStatusText[jobStatusIndex] }}</text>
          <image class="arrow-icon" src="/static/icons/arrow-right.png" mode="widthFix" alt="箭头"></image>
        </view>
      </picker>
    </view>

    <!-- 个人优势 -->
    <view class="section" @click="openAdvantagePopup">
      <text class="section-title">个人优势</text>
      <text class="content">{{ userInfo.advantage || '点击编辑' }}</text>
      <image 
        class="edit-btn" 
        src="/static/icons/edit.png" 
        mode="widthFix" 
        @click.stop="openAdvantagePopup" 
        alt="编辑"
      ></image>
    </view>
    
    <!-- 个人优势编辑弹窗 -->
    <view class="popup-mask" v-if="showAdvantagePopup">
      <view class="popup">
        <text class="popup-title">编辑个人优势</text>
        <textarea 
          class="popup-textarea" 
          v-model="tempAdvantage"
          placeholder="请输入个人优势"
          maxlength="500"
        ></textarea>
        <view class="popup-btn-group">
          <button class="popup-btn cancel-btn" @click="showAdvantagePopup = false">取消</button>
          <button class="popup-btn confirm-btn" @click="confirmAdvantage">确认</button>
        </view>
      </view>
    </view>

    <!-- 资格证书 -->
    <view class="section" @click="showCertPopup = true">
      <text class="section-title">资格证书</text>
      <text class="content" v-if="userInfo.certificate">{{ userInfo.certificate }}</text>
      <text class="content" v-else>点击添加</text>
      <image class="edit-btn" src="/static/icons/edit.png" mode="widthFix" @click.stop="showCertPopup = true" alt="编辑"></image>
    </view>

    <!-- 资格证书编辑弹窗 -->
    <view class="popup-mask" v-if="showCertPopup">
      <view class="popup">
        <text class="popup-title">编辑资格证书</text>
        <textarea 
          class="popup-textarea" 
          v-model="tempCertificates"
          placeholder="请输入资格证书，多个以、分隔"
        ></textarea>
        <view class="popup-btn-group">
          <button class="popup-btn cancel-btn" @click="showCertPopup = false">取消</button>
          <button class="popup-btn confirm-btn" @click="confirmCert">确认</button>
        </view>
      </view>
    </view>

    <!-- 项目经历 -->
    <view class="section" @click="openProjectPopup">
      <text class="section-title">项目经历</text>
      <view class="project-experience-list" v-if="projects.length > 0">
        <view 
          class="project-item" 
          v-for="(project, index) in projects" 
          :key="project.projectHistoryId"
        >
          <text class="project-name">{{ project.projectName }}</text>
          <text class="project-duty">职责：{{ project.duty }}</text>
        </view>
      </view>
      <text class="content" v-else>点击添加</text>
      <image class="edit-btn" src="/static/icons/edit.png" mode="widthFix" @click.stop="openProjectPopup" alt="编辑"></image>
    </view>

    <!-- 教育经历 -->
    <view class="section" @click="openEduPopup">
      <text class="section-title">教育经历</text>
      <view class="edu-experience-list" v-if="educations.length > 0">
        <view 
          class="edu-item" 
          v-for="(edu, index) in educations" 
          :key="edu.educationBackgroundId"
        >
          {{ edu.schoolName }} {{ edu.startTime }}~{{ edu.endTime }} · {{ edu.professional }}
        </view>
      </view>
      <text class="content" v-else>点击添加</text>
      <image class="edit-btn" src="/static/icons/edit.png" mode="widthFix" @click.stop="openEduPopup" alt="编辑"></image>
    </view>

    <!-- 工作经历 -->
    <view class="section" @click="openWorkPopup">
      <text class="section-title">工作经历</text>
      <view class="work-experience-list" v-if="works.length > 0">
        <view class="work-item" v-for="(work, index) in works" :key="work.workHistoryId">
          <text class="work-position">{{ work.workName }}</text>
          <text class="work-time">{{ work.workTime }}</text>
          <text class="work-desc">{{ work.workInfo }}</text>
        </view>
      </view>
      <text class="content" v-else>点击添加</text>
      <image class="edit-btn" src="/static/icons/edit.png" mode="widthFix" @click.stop="openWorkPopup" alt="编辑"></image>
    </view>

    <!-- 项目经历编辑弹窗 -->
    <view class="popup-mask" v-if="showProjectPopup" @click="closeProjectPopup">
      <view class="popup project-popup" @click.stop>
        <text class="popup-title">编辑项目经历</text>
        
        <!-- 标签页导航 -->
        <view class="tabs-nav">
          <view 
            class="tab-item" 
            v-for="(project, index) in projects" 
            :key="project.projectHistoryId"
            :class="{ 'active': currentProjectTab === index }"
            @click="currentProjectTab = index"
          >
            <text>项目 {{ index + 1 }}</text>
            <image 
              class="tab-delete" 
              src="/static/icons/delete.png" 
              mode="widthFix"
              @click.stop="deleteProjectTab(index)"
              v-if="projects.length > 1"
              alt="删除"
            ></image>
          </view>
          <view class="tab-add" @click="addProjectTab">+ 添加项目</view>
        </view>
        
        <!-- 标签页内容 -->
        <view class="tab-content">
          <view class="form-item">
            <text class="form-label">项目名称：</text>
            <input 
              class="form-input" 
              v-model="projects[currentProjectTab].projectName" 
              placeholder="请输入项目名称"
              @input="onProjectInput(currentProjectTab, 'projectName', $event)"
            />
          </view>
          <view class="form-item">
            <text class="form-label">担任职责：</text>
            <textarea 
              class="form-textarea" 
              v-model="projects[currentProjectTab].duty" 
              placeholder="请详细描述在项目中担任的职责、工作内容和成果"
              @input="onProjectInput(currentProjectTab, 'duty', $event)"
            ></textarea>
          </view>
        </view>
        
        <view class="popup-btn-group">
          <button class="popup-btn cancel-btn" @click="closeProjectPopup">取消</button>
          <button class="popup-btn confirm-btn" @click="confirmProject(projects[currentProjectTab].projectHistoryId)">确认</button>
        </view>
      </view>
    </view>

    <!-- 教育经历编辑弹窗 -->
    <view class="popup-mask" v-if="showEduPopup" @click="closeEduPopup">
      <view class="popup edu-popup" @click.stop>
        <text class="popup-title">编辑教育经历</text>
        
        <!-- 标签页导航 -->
        <view class="tabs-nav">
          <view 
            class="tab-item" 
            v-for="(edu, index) in educations" 
            :key="edu.educationBackgroundId"
            :class="{ 'active': currentEduTab === index }"
            @click="currentEduTab = index"
          >
            <text>经历 {{ index + 1 }}</text>
            <image 
              class="tab-delete" 
              src="/static/icons/delete.png" 
              mode="widthFix"
              @click.stop="deleteEduTab(index)"
              v-if="educations.length > 1"
              alt="删除"
            ></image>
          </view>
          <view class="tab-add" @click="addEduTab">+ 添加经历</view>
        </view>
        
        <!-- 标签页内容 -->
        <view class="tab-content">
          <view class="form-item">
            <text class="form-label">学校名称：</text>
            <input 
              class="form-input" 
              v-model="educations[currentEduTab].schoolName" 
              placeholder="请输入学校名称"
              @input="onEduInput(currentEduTab, 'schoolName', $event)"
            />
          </view>
          <view class="form-item">
            <text class="form-label">专业：</text>
            <input 
              class="form-input" 
              v-model="educations[currentEduTab].professional" 
              placeholder="请输入专业"
              @input="onEduInput(currentEduTab, 'professional', $event)"
            />
          </view>
          <view class="form-item">
            <text class="form-label">开始时间：</text>
            <input 
              class="form-input" 
              v-model="educations[currentEduTab].startTime" 
              placeholder="例如：2022.02.05"
              @input="onEduInput(currentEduTab, 'startTime', $event)"
            />
          </view>
          <view class="form-item">
            <text class="form-label">结束时间：</text>
            <input 
              class="form-input" 
              v-model="educations[currentEduTab].endTime" 
              placeholder="例如：2025.02.05"
              @input="onEduInput(currentEduTab, 'endTime', $event)"
            />
          </view>
        </view>
        
        <view class="popup-btn-group">
          <button class="popup-btn cancel-btn" @click="closeEduPopup">取消</button>
          <button class="popup-btn confirm-btn" @click="confirmEdu(educations[currentEduTab].educationBackgroundId)">确认</button>
        </view>
      </view>
    </view>

    <!-- 工作经历编辑弹窗 -->
    <view class="popup-mask" v-if="showWorkPopup" @click="closeWorkPopup">
      <view class="popup work-popup" @click.stop>
        <text class="popup-title">编辑工作经历</text>
        
        <!-- 标签页导航 -->
        <view class="tabs-nav">
          <view 
            class="tab-item" 
            v-for="(work, index) in works" 
            :key="work.workHistoryId"
            :class="{ 'active': currentWorkTab === index }"
            @click="currentWorkTab = index"
          >
            <text>经历 {{ index + 1 }}</text>
            <image 
              class="tab-delete" 
              src="/static/icons/delete.png" 
              mode="widthFix"
              @click.stop="deleteWorkTab(index)"
              v-if="works.length > 1"
              alt="删除"
            ></image>
          </view>
          <view class="tab-add" @click="addWorkTab">+ 添加经历</view>
        </view>
        
        <!-- 标签页内容 -->
        <view class="tab-content">
          <view class="form-item">
            <text class="form-label">时间区间：</text>
            <input 
              class="form-input" 
              v-model="works[currentWorkTab].workTime" 
              placeholder="例如：2023.01~2025.01"
              @input="onWorkInput(currentWorkTab, 'workTime', $event)"
            />
          </view>
          <view class="form-item">
            <text class="form-label">职位名称：</text>
            <input 
              class="form-input" 
              v-model="works[currentWorkTab].workName" 
              placeholder="请输入职位名称"
              @input="onWorkInput(currentWorkTab, 'workName', $event)"
            />
          </view>
          <view class="form-item">
            <text class="form-label">工作描述：</text>
            <textarea 
              class="form-textarea" 
              v-model="works[currentWorkTab].workInfo" 
              placeholder="请描述工作内容和职责"
              @input="onWorkInput(currentWorkTab, 'workInfo', $event)"
            ></textarea>
          </view>
        </view>
        
        <view class="popup-btn-group">
          <button class="popup-btn cancel-btn" @click="closeWorkPopup">取消</button>
          <button class="popup-btn confirm-btn" @click="confirmWork(works[currentWorkTab].workHistoryId)">确认</button>
        </view>
      </view>
    </view>

  </view>
</template>

<script>
import state from '../../store/state';
import {
  updateJobStatus,
  updateAdvantage,
  getAdvAndCert,
  updateCertificates,
  getProjectHistory,
  updateProject,
  getEducationBackground,  // 获取教育经历接口
  updateEducation,  // 更新教育经历接口
  getWorkHistory,  // 获取工作经历接口
  updateWork  ,// 更新工作经历接口
  deleteProject,//删除项目经历
  deleteEducation,//删除教育背景
  deleteWork,//删除工作经历
  addProject,//新增项目经历
  addEducation,//新增教育背景
  addWork,//新增工作经历
} from '@/api/resume.js'

export default {
  data() {
    return {
		userId:null,
      // 个人信息数据
      userInfo: {
        name: '',
        age: '',
        degree: '',
        telephone: '',
        headIcon: '',
        jobSearchStatus: '',
        advantage: '', 
        certificate: '', 
        resumeId: null,  // 存储resumeId供各模块使用
      },
	   // 学历状态映射表
	      degreeMap: {
	        0: '中学',
	        1: '高中',
	        2: '中专',
	        3: '大专',
	        4: '本科',
	        5: '硕士',
	        6: '博士'
	      },
	  
      // 求职状态文本映射
      jobSearchStatusMap: {
        null: '请填写',
        0: '在职',
        1: '离职',
        2: '在校',
        3: '离校'
      },
      jobSearchStatusText: ['请填写', '在职', '离职', '在校', '离校'],
      jobStatusIndex: 0,
      // 弹窗控制
      showAdvantagePopup: false,
      showCertPopup: false,
      showProjectPopup: false,
      showEduPopup: false,
      showWorkPopup: false,
      // 临时编辑内容
      tempAdvantage: '',
      tempCertificates: '',
      // 经历数据（确保包含ID字段）
      projects: [],  // 每项含 projectHistoryId
      educations: [],  // 每项含 educationBackgroundId
      works: [],  // 每项含 workHistoryId
	  originalEducations: [], // 存储原始教育经历数据用于比对
	  originalWorks: [],       // 存储原始工作经历数据
	  originalProjects: [],     // 存储原始项目经历数据
      // 标签页控制
      currentWorkTab: 0,
      currentEduTab: 0,
      currentProjectTab: 0
    }
  },
  onLoad(val) {
	  this.userId = val.userId;
    this.loadUserInfo();
    this.loadAdvantageAndCert();  // 加载resumeId后触发其他接口
  },
  methods: {
	  openProjectPopup(){
		  this.showProjectPopup = true;
		      // 深拷贝当前项目经历数据作为原始数据
		      this.originalProjects = JSON.parse(JSON.stringify(this.projects));
	  },
	  /**
	     * 判断项目经历是否有修改
	     * @returns {boolean} 是否有修改
	     */
	    hasProjectChanged() {
	      // 如果数据长度变化，直接认为有修改
	      if (this.projects.length !== this.originalProjects.length) {
	        return true;
	      }
	      
	      // 逐条比对数据
	      for (let i = 0; i < this.projects.length; i++) {
	        const current = this.projects[i];
	        const original = this.originalProjects[i];
	        
	        // 比对每个关键字段
	        if (
	          current.projectName !== original.projectName ||
	          current.duty !== original.duty
	        ) {
	          return true;
	        }
	      }
	      
	      // 没有任何修改
	      return false;
	    },
	  openWorkPopup(){
		 this.showWorkPopup = true;
		     // 深拷贝当前工作经历数据作为原始数据
		     this.originalWorks = JSON.parse(JSON.stringify(this.works)); 
	  },
	  openEduPopup(){
		   this.showEduPopup = true;
		      // 深拷贝当前教育经历数据作为原始数据
		      this.originalEducations = JSON.parse(JSON.stringify(this.educations));
	  },
	  /**
	     * 判断工作经历是否有修改
	     * @returns {boolean} 是否有修改
	     */
	    hasWorkChanged() {
	      // 如果数据长度变化，直接认为有修改
	      if (this.works.length !== this.originalWorks.length) {
	        return true;
	      }
	      
	      // 逐条比对数据
	      for (let i = 0; i < this.works.length; i++) {
	        const current = this.works[i];
	        const original = this.originalWorks[i];
	        
	        // 比对每个关键字段
	        if (
	          current.workName !== original.workName ||
	          current.workTime !== original.workTime ||
	          current.workInfo !== original.workInfo
	        ) {
	          return true;
	        }
	      }
	      
	      // 没有任何修改
	      return false;
	    },
	  /**
	     * 判断教育经历是否有修改
	     * @returns {boolean} 是否有修改
	     */
	    hasEducationChanged() {
	      // 如果数据长度变化，直接认为有修改
	      if (this.educations.length !== this.originalEducations.length) {
	        return true;
	      }
	      
	      // 逐条比对数据
	      for (let i = 0; i < this.educations.length; i++) {
	        const current = this.educations[i];
	        const original = this.originalEducations[i];
	        
	        // 比对每个关键字段
	        if (
	          current.schoolName !== original.schoolName ||
	          current.professional !== original.professional ||
	          current.startTime !== original.startTime ||
	          current.endTime !== original.endTime
	        ) {
	          return true;
	        }
	      }
	      
	      // 没有任何修改
	      return false;
	    },
    // ========================= 项目经历相关 =========================
    // 加载项目经历（确保获取projectHistoryId）
    loadProjectExperiences() {
      if (!this.userInfo.resumeId) {
        // 等待resumeId加载完成
        setTimeout(() => this.loadProjectExperiences(), 1000);
        return;
      }
      
      getProjectHistory({ resumeId: this.userInfo.resumeId })
        .then(res => {
          if (res.code === 200) {
            this.projects = res.data || [];
            // 如果没有数据，初始化一个空项目（带临时ID）
            if (this.projects.length === 0) {
              this.addProjectTab(true);
            }
          } else {
            uni.showToast({ title: res.msg || '加载项目经历失败', icon: 'none' });
          }
        })
        .catch(e => {
          uni.showToast({ title: '网络错误，无法加载项目经历', icon: 'none' });
        });
    },
    
    // 保存项目经历到后端（携带projectHistoryId）
    async confirmProject(val) {
		// 先判断是否有修改
		    if (!this.hasProjectChanged()) {
		      uni.showToast({ 
		        title: '未检测到任何修改', 
		        icon: 'none',
		        duration: 2000
		      });
		      return; // 拦截后续操作
		    }
      if (!state.userInfo.userId || !this.userInfo.resumeId) {
        uni.showToast({ title: '必要信息未加载', icon: 'none' });
        return;
      }
      
      // 验证项目数据（保留ID）
      const validProjects = this.projects.filter(p => 
        p.projectName && p.projectName.trim() && 
        p.duty && p.duty.trim() &&
        p.projectHistoryId  // 确保ID存在
      );
      
      if (validProjects.length === 0) {
        uni.showToast({ title: '请至少填写一个有效的项目经历', icon: 'none' });
        return;
      }
	  updateProject(validProjects)
	  .then(res =>{
		  if (res.code === 200){
			  this.projects = res.data || validProjects;
			  this.showProjectPopup = false;
			  uni.showToast({ title: '项目经历修改成功', icon: 'success' });
		  }else{
			  uni.showToast({ title: res.msg || '保存项目经历失败', icon: 'none' });
		  }
	  })
      .catch(e =>{
		  uni.showToast({ title: '网络错误，保存失败', icon: 'none' });
	  })
    },
    
    closeProjectPopup() {
      this.showProjectPopup = false;
    },
    
    onProjectInput(index, field, e) {
      this.$set(this.projects[index], field, e.target.value);
    },
    
    // 修改项目经历添加方法（直接插入数据库，用真实ID渲染）
    addProjectTab(isInit = false) {
      // 验证resumeId是否存在（初始化场景也需要resumeId，否则无法关联简历）
      if (!this.userInfo.resumeId) {
        uni.showToast({ title: '简历信息未加载', icon: 'none' });
        return;
      }          
        this.addRealProject();     
    },
    
    // 核心：调用后端接口添加真实数据，成功后再渲染前端
    addRealProject() {
      // 显示加载中，避免重复点击
      uni.showLoading({ title: '添加中...', mask: true });
    
      // 调用新增接口（直接插入数据库）
      addProject({
        resumeId: this.userInfo.resumeId, // 必传：关联简历ID
        projectName: "", // 初始为空，后续编辑
        duty: ""
      }).then(res => {
        uni.hideLoading();
        if (res.code === 200) {
          // 接口成功且返回真实ID：添加到前端列表
          const realProject = {
            projectHistoryId: res.data, // 后端真实ID
            resumeId: this.userInfo.resumeId, // 关联的简历ID
            projectName: "", // 初始为空
            duty: ""
          };
          this.projects.push(realProject);
          // 切换到新增的项目标签页
          this.currentProjectTab = this.projects.length - 1;
          // 更新原始数据快照
          this.originalProjects = JSON.parse(JSON.stringify(this.projects));
          uni.showToast({ title: '项目经历添加成功', icon: 'success' });
        } else {
          // 接口失败：提示错误（无前端数据添加，无需回滚）
          uni.showToast({ title: res.msg || '添加失败', icon: 'none' });
        }
      })
    },
    
    deleteProjectTab(index) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个项目经历吗？',
        success: (res) => {
          // 关键：只有用户点击“确定”时才执行删除
          if (res.confirm) { 
            deleteProject(this.projects[index].projectHistoryId)
              .then(res => {
                if (res.code === 200) { // 建议用code判断，更规范
                  // 后端删除成功后，更新前端数据
                  this.projects.splice(index, 1);
                  if (this.currentProjectTab >= index) {
                    this.currentProjectTab = Math.max(0, this.currentProjectTab - 1);
                  }
                  this.originalProjects = JSON.parse(JSON.stringify(this.projects));
                  uni.showToast({ title: '删除成功', icon: 'success' });
                } else {
                  uni.showToast({ title: res.msg || '删除失败', icon: 'none' });
                }
              })
              .catch(e => {
                uni.showToast({ title: '网络错误，删除失败', icon: 'none' });
              });
          } 
        }
      });
    },

    // ========================= 教育经历相关 =========================
    // 加载教育经历（确保获取educationBackgroundId）
    loadEducationExperiences() {
		
      if (!this.userInfo.resumeId) {
        // 等待resumeId加载完成
        setTimeout(() => this.loadEducationExperiences(), 1000);
        return;
      }
      
      getEducationBackground({ resumeId: this.userInfo.resumeId })
        .then(res => {
          if (res.code === 200) {
            this.educations = res.data || validEducations;
            // 如果没有数据，初始化一个空教育经历（带临时ID）
            if (this.educations.length === 0) {
              this.addEduTab(true);
            }
          } else {
            uni.showToast({ title: res.msg || '加载教育经历失败', icon: 'none' });
          }
        })
        .catch(e => {
          uni.showToast({ title: '网络错误，无法加载教育经历', icon: 'none' });
        });
    },
    
    // 保存教育经历到后端（携带educationBackgroundId）
    async confirmEdu(val) {
		 // 先判断是否有修改
		  if (!this.hasEducationChanged()) {
		    uni.showToast({ 
		      title: '未检测到任何修改', 
		      icon: 'none',
		      duration: 2000
		    });
		    return; // 拦截后续操作
		  }
      if (!state.userInfo.userId || !this.userInfo.resumeId) {
        uni.showToast({ title: '必要信息未加载', icon: 'none' });
        return;
      }
      console.log(val)
      // 验证教育经历数据（保留ID）
      const validEducations = this.educations.filter(edu => {
        return edu.schoolName?.trim() && 
               edu.professional?.trim() && 
               edu.startTime?.trim() && 
               edu.educationBackgroundId;  // 确保ID存在
      });
      
      if (validEducations.length === 0) {
        uni.showToast({ title: '请至少填写一个有效的教育经历', icon: 'none' });
        return;
      }
      updateEducation(validEducations)
      .then(res =>{
		  
        if (res.code === 200) {
          // 用后端返回的带正式ID的数据更新本地
          this.educations = res.data|| validEducations; 
          this.showEduPopup = false;
          uni.showToast({ title: '教育经历保存成功', icon: 'success' });
        } else {
          uni.showToast({ title: res.msg || '保存教育经历失败', icon: 'none' });
        }
      })
      .catch(e =>{
        uni.showToast({ title: '网络错误，保存失败', icon: 'none' });
      })
    },
    
    closeEduPopup() {
      this.showEduPopup = false;
    },
    
    onEduInput(index, field, e) {
      this.$set(this.educations[index], field, e.target.value);
    },
    
    // 修改教育经历添加方法（调用后端接口获取真实ID）
    addEduTab(isInit = false) {
      // 验证resumeId是否存在
      if (!this.userInfo.resumeId) {
        uni.showToast({ title: '简历信息未加载', icon: 'none' });
        return;
      }
    
      // 调用真实添加接口
      this.addRealEducation();
    },
    
    // 核心：调用后端接口添加教育经历
    addRealEducation() {
      // 显示加载中状态，防止重复提交
      uni.showLoading({ title: '添加中...', mask: true });
    
      // 调用新增接口
      addEducation({
        resumeId: this.userInfo.resumeId, // 必传：关联简历ID
        schoolName: "", // 初始为空，后续编辑
        professional: "",
        startTime: "2022.06.22".replace(/\./g, "-"),
        endTime: null
      }).then(res => {
        uni.hideLoading();
        if (res.code === 200) {
          // 接口成功：添加到前端列表
          const realEducation = {
            educationBackgroundId: res.data, // 后端返回的真实ID
            resumeId: this.userInfo.resumeId,
            schoolName: "",
            professional: "",
            startTime: "2022.06.22".replace(/\./g, "-"),
            endTime: null
          };
          this.educations.push(realEducation);
          // 切换到新增的标签页
          this.currentEduTab = this.educations.length - 1;
          // 更新原始数据快照
          this.originalEducations = JSON.parse(JSON.stringify(this.educations));
          uni.showToast({ title: '教育经历添加成功', icon: 'success' });
        } else {
          // 接口失败：仅提示错误
          uni.showToast({ title: res.msg || '添加失败', icon: 'none' });
        }
      }).catch(e => {
        uni.hideLoading();
        uni.showToast({ title: '网络错误，添加失败', icon: 'none' });
      });
    },
    
    deleteEduTab(index) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个教育经历吗？',
        success: (res) => { // 移除多余的async（未使用await）
          if (res.confirm) {           
            // 调用删除接口
            deleteEducation(this.educations[index].educationBackgroundId)
              .then(res => {
                if (res.code === 200) {
                  // 后端删除成功后更新前端
                  this.educations.splice(index, 1);
                  
                  // 调整当前标签页索引
                  if (this.currentEduTab >= index) {
                    this.currentEduTab = Math.max(0, this.currentEduTab - 1);
                  }
                  
                  // 更新原始数据快照
                  this.originalEducations = JSON.parse(JSON.stringify(this.educations));
                  
                  uni.showToast({ title: '删除成功', icon: 'success' });
                } else {
                  uni.showToast({ title: res.msg || '删除失败', icon: 'none' });
                }
              })
              .catch(error => {
                console.error('删除失败', error);
                uni.showToast({ title: '网络错误，删除失败', icon: 'none' });
              });
          }
        } // 闭合success回调
      }); // 闭合uni.showModal调用
    }, 



    // ========================= 工作经历相关 =========================
    // 加载工作经历（确保获取workHistoryId）
    loadWorkExperiences() {
      if (!this.userInfo.resumeId) {
        // 等待resumeId加载完成
        setTimeout(() => this.loadWorkExperiences(), 1000);
        return;
      }
      
      getWorkHistory({ resumeId: this.userInfo.resumeId })
        .then(res => {
          if (res.code === 200) {
            this.works = res.data || [];
            // 如果没有数据，初始化一个空工作经历（带临时ID）
            if (this.works.length === 0) {
              this.addWorkTab(true);
            } else {
              this.currentWorkTab = Math.min(this.currentWorkTab, this.works.length - 1);
            }
          } else {
            uni.showToast({ title: res.msg || '加载工作经历失败', icon: 'none' });
            if (this.works.length === 0) {
              this.addWorkTab(true);
            }
          }
        })
        .catch(e => {
          uni.showToast({ title: '网络错误，无法加载工作经历', icon: 'none' });
          if (this.works.length === 0) {
            this.addWorkTab(true);
          }
        });
    },
    
    // 保存工作经历到后端（携带workHistoryId）
    async confirmWork(val) {
		// 先判断是否有修改
		    if (!this.hasWorkChanged()) {
		      uni.showToast({ 
		        title: '未检测到任何修改', 
		        icon: 'none',
		        duration: 2000
		      });
		      return; // 拦截后续操作
		    }
      if (!state.userInfo.userId || !this.userInfo.resumeId) {
        uni.showToast({ title: '必要信息未加载', icon: 'none' });
        return;
      }
      
      // 验证工作经历数据（保留ID）
      const validWorks = this.works.filter(work => 
        work.workName && work.workName.trim() && 
        work.workTime && work.workTime.trim() &&
        work.workInfo && work.workInfo.trim() &&
        work.workHistoryId  // 确保ID存在
      );
      
      if (validWorks.length === 0) {
        uni.showToast({ title: '请至少填写一个有效的工作经历', icon: 'none' });
        return;
      }
      updateWork(validWorks).then(res =>{
		  if(res.code === 200){
			  this.works = res.data || validWorks;
			  this.showWorkPopup = false;
			   uni.showToast({ title: '工作经历修改成功', icon: 'success' });
		  }else{
			  uni.showToast({ title: res.msg || '保存工作经历失败', icon: 'none' });
		  }
	  })
	  .catch(e =>{
		  uni.showToast({ title: '网络错误，保存失败', icon: 'none' });
	  })
    },
    
    closeWorkPopup() {
      this.showWorkPopup = false;
    },
    
    onWorkInput(index, field, e) {
      if (index >= 0 && index < this.works.length) {
        this.$set(this.works[index], field, e.target.value);
      }
    },
    
    // 修改工作经历添加方法（调用后端接口获取真实ID）
    addWorkTab(isInit = false) {
      // 验证resumeId是否存在
      if (!this.userInfo.resumeId) {
        uni.showToast({ title: '简历信息未加载', icon: 'none' });
        return;
      }
    
      // 调用真实添加接口
      this.addRealWork();
    },
    
    // 核心：调用后端接口添加工作经历
    addRealWork() {
      // 显示加载中状态
      uni.showLoading({ title: '添加中...', mask: true });
    
      // 调用新增接口
      addWork({
        resumeId: this.userInfo.resumeId, // 必传：关联简历ID
        workTime: "", // 初始为空，后续编辑
        workName: "",
        workInfo: ""
      }).then(res => {
        uni.hideLoading();
        if (res.code === 200) {
          // 接口成功：添加到前端列表
          const realWork = {
            workHistoryId: res.data, // 后端返回的真实ID
            resumeId: this.userInfo.resumeId,
            workTime: "",
            workName: "",
            workInfo: ""
          };
          this.works.push(realWork);
          // 切换到新增的标签页
          this.currentWorkTab = this.works.length - 1;
          // 更新原始数据快照
          this.originalWorks = JSON.parse(JSON.stringify(this.works));
          uni.showToast({ title: '工作经历添加成功', icon: 'success' });
        } else {
          // 接口失败：仅提示错误
          uni.showToast({ title: res.msg || '添加失败', icon: 'none' });
        }
      }).catch(e => {
        uni.hideLoading();
        uni.showToast({ title: '网络错误，添加失败', icon: 'none' });
      });
    },
    
    deleteWorkTab(index) {
      // 校验索引有效性
      if (index < 0 || index >= this.works.length) {
        uni.showToast({ title: '数据异常', icon: 'none' });
        return;
      }
    
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个工作经历吗？',
        success: (res) => { 
          // 只有用户确认时才执行删除
          if (res.confirm) {
            deleteWork(this.works[index].workHistoryId)
              .then(res => {
                if (res.code === 200) {
                  // 后端删除成功后更新前端数据
                  this.works.splice(index, 1);
                  
                  // 调整当前标签页索引
                  if (this.currentWorkTab >= index) {
                    this.currentWorkTab = Math.max(0, this.currentWorkTab - 1);
                  }
                  this.currentWorkTab = Math.min(this.currentWorkTab, this.works.length - 1);
                  
                  // 更新原始数据快照
                  this.originalWorks = JSON.parse(JSON.stringify(this.works));
                  uni.showToast({ title: '删除成功', icon: 'success' });
                } else {
                  uni.showToast({ title: res.msg || '删除失败', icon: 'none' });
                }
              })
              .catch(error => {
                uni.showToast({ title: '网络错误，删除失败', icon: 'none' });
              });
          }
        } // 闭合success回调
      }); // 闭合showModal调用
    }, // 闭合方法


    // ========================= 其他通用方法 =========================
    // 确认保存个人优势
    async confirmAdvantage() {
      if (!state.userInfo.userId) {
        uni.showToast({ title: '用户信息未加载', icon: 'none' });
        return;
      }
      
      updateAdvantage({
        userId: state.userInfo.userId,
        advantage: this.tempAdvantage.trim()
      })
      .then(res => {
        if (res.code === 200) {
          this.userInfo.advantage = this.tempAdvantage;
          this.showAdvantagePopup = false;
          uni.showToast({ title: '保存成功', icon: 'success' });
        } else {
          uni.showToast({ title: res.msg || '保存失败', icon: 'none' });
        }
      })
      .catch(e => {
        uni.showToast({ title: '网络错误', icon: 'none' });
      });
    },
    
    // 打开个人优势编辑弹窗
    openAdvantagePopup() {
      this.tempAdvantage = this.userInfo.advantage || '';
      this.showAdvantagePopup = true;
    },
    
    // 加载个人优势、资格证书和resumeId
    async loadAdvantageAndCert() {
      // 等待用户ID加载
      let retryCount = 0;
      const maxRetry = 10;
      const checkUserId = () => {
        return new Promise((resolve) => {
          const interval = setInterval(() => {
            retryCount++;
            if (state.userInfo.userId || retryCount >= maxRetry) {
              clearInterval(interval);
              resolve();
            }
          }, 500);
        });
      };
      await checkUserId();

      if (!state.userInfo.userId) {
        setTimeout(() => this.loadAdvantageAndCert(), 2000);
        return;
      }    
      
      getAdvAndCert({ userId: state.userInfo.userId })
        .then(res => {
          if (res.code === 200) {
            const { advantage, certificate, resumeId } = res.data;
            
            // 存储resumeId供其他接口使用
            this.userInfo.resumeId = res.data.resumeId;
            
            // 更新个人优势
            this.userInfo.advantage = res.data.advantage || '';
            this.tempAdvantage = this.userInfo.advantage;
            
            // 更新资格证书
            this.userInfo.certificate = res.data.certificate || '';
            this.tempCertificates = this.userInfo.certificate;
            
            // 加载各经历数据（包含ID）
            this.loadProjectExperiences();
            this.loadEducationExperiences();
            this.loadWorkExperiences();
          }
        })
        .catch(e => {
          console.error('加载优势和证书失败:', e);
          uni.showToast({ title: '数据加载失败', icon: 'none' });
        });
    },
    
    // 确认保存资格证书
    async confirmCert() {
      if (!state.userInfo.userId) {
        uni.showToast({ title: '用户信息未加载', icon: 'none' });
        return;
      }
      
      const certValue = this.tempCertificates.trim();
      
      updateCertificates({
        userId: state.userInfo.userId,
        certificate: certValue
      })
      .then(res => {
        if (res.code === 200) {
          this.userInfo.certificate = certValue;
          this.showCertPopup = false;
          uni.showToast({ title: '资格证书已保存', icon: 'success' });
        } else {
          uni.showToast({ title: res.msg || '保存失败', icon: 'none' });
        }
      })
      .catch(e => {
        uni.showToast({ title: '网络错误', icon: 'none' });
      });
    },
    
    // 求职状态相关方法
    setJobStatusIndex() {
      const statusValue = this.userInfo.jobSearchStatus;
      const indexMap = {
        null: 0,
        0: 1,
        1: 2,
        2: 3,
        3: 4
      };
      this.jobStatusIndex = indexMap[statusValue] || 0;
    },
    
    onJobStatusChange(e) {
      const selectedIndex = e.detail.value;
      this.jobStatusIndex = selectedIndex;
      
      const valueMap = [null, 0, 1, 2, 3];
      this.userInfo.jobSearchStatus = valueMap[selectedIndex];
      this.saveJobStatusToServer();
    },
    
    saveJobStatusToServer() {
      updateJobStatus({
        jobSearchStatus: this.userInfo.jobSearchStatus,
        userId: state.userInfo.userId
      })
      .then(res => {
        if (res.code === 200) {
          uni.showToast({ title: '修改求职状态成功', icon: 'success' });
        } else {
          uni.showToast({ title: res.msg || '修改失败', icon: 'none' }); 
        }
      })
      .catch(e => {
        uni.showToast({ title: '网络错误', icon: 'none' });
      });
    },
    
    // 头像加载失败处理
    handleAvatarError() {
      this.userInfo.headIcon = "/static/avatar/头像.png";
    },
    
    // 加载用户基本信息
    loadUserInfo() {
      if (!state.userInfo) {
        setTimeout(() => {
          this.loadUserInfo();
        }, 2000);
      } else {
        this.userInfo.username = state.userInfo.username;
        this.userInfo.telephone = state.userInfo.telephone;
        this.userInfo.age = state.userInfo.age;
        this.userInfo.headIcon = state.userInfo.headIcon;
        this.userInfo.degree = state.userInfo.degree;
        this.userInfo.jobSearchStatus = state.userInfo.jobSearchStatus;
        this.setJobStatusIndex();
      }
    },
    
    // 导航方法
    navigateBack() {
      uni.navigateBack();
    },
    
    navigateToPersonalEdit() {
      uni.navigateTo({
        url: '/pages/zj/PersonInfo'
      });
    }
  }
}
</script>

<style scoped>
.resume-page {
  background-color: #fff;
  min-height: 100vh;
  padding: 15px;
  box-sizing: border-box;
}

.title-bar {
  height: 44px;
  line-height: 44px;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  position: relative;
  padding-left: 15px;
}

.back-icon {
  width: 16px;
  height: 16px;
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
}

.title {
  font-size: 17px;
  font-weight: bold;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.personal-info {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.info-left {
  flex: 1;
  margin-right: 10px;
}

.name-area {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.name {
  font-size: 18px;
  font-weight: bold;
}

.edit-icon {
  width: 20px;
  height: 20px;
  margin-left: 5px;
}

.other-info {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.contact-info {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.contact-icon {
  width: 16px;
  height: 16px;
  margin-right: 3px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
}

.section {
  padding: 15px 0;
  border-bottom: 1px solid #eee;
  display: flex;
  flex-direction: column;
  position: relative;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.content {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
}

.job-status {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  color: #333;
}

.arrow-icon {
  width: 16px;
  height: 16px;
}

.edit-btn {
  width: 20px;
  height: 20px;
  position: absolute;
  right: 0;
  top: 15px;
}

.project-experience-list,
.work-experience-list,
.edu-experience-list {
  width: 100%;
}

.project-item,
.work-item,
.edu-item {
  margin-bottom: 15px;
  padding-left: 5px;
  border-left: 2px solid #007aff;
}

.project-item:last-child,
.work-item:last-child,
.edu-item:last-child {
  margin-bottom: 0;
}

.project-name,
.work-position {
  font-size: 15px;
  font-weight: bold;
  display: block;
  margin-bottom: 5px;
}

.project-duty {
  font-size: 13px;
  color: #666;
  display: block;
  line-height: 1.6;
}

.work-time {
  font-size: 13px;
  color: #666;
  display: block;
  margin-bottom: 5px;
}

.work-desc {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
}

.edu-item {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
}

.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.popup {
  width: 80%;
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
}

.edu-popup, .work-popup, .project-popup {
  width: 90%;
  max-height: 85vh;
  overflow-y: auto;
  box-sizing: border-box;
}

.popup-title {
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 15px;
}

.popup-textarea {
  width: 100%;
  height: 100px;
  border: 1px solid #eee;
  border-radius: 5px;
  padding: 10px;
  box-sizing: border-box;
  margin-bottom: 15px;
}

.popup-btn-group {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
}

.popup-btn {
  width: 45%;
  border-radius: 5px;
  padding: 10px 0;
  font-size: 14px;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #333;
}

.confirm-btn {
  background-color: #007aff;
  color: #fff;
}

.tabs-nav {
  display: flex;
  gap: 10px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
  overflow-x: auto;
  margin-bottom: 15px;
  white-space: nowrap;
}

.tab-item {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 6px 12px;
  background-color: #f5f5f5;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
}

.tab-item.active {
  background-color: #007aff;
  color: white;
}

.tab-delete {
  width: 16px;
  height: 16px;
}

.tab-add {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  padding: 6px 0;
  background-color: #f0f7ff;
  color: #007aff;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
}

.tab-content {
  width: 100%;
}

.form-item {
  margin-bottom: 15px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-label {
  font-size: 14px;
  color: #666;
}

.form-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 5px;
  font-size: 14px;
}

.form-textarea {
  width: 100%;
  height: 100px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 5px;
  font-size: 14px;
  box-sizing: border-box;
  resize: none;
}
</style>
